package com.ncu.gulimall.order.interceptor;

import com.ncu.gulimall.common.constant.AuthServerConstant;
import com.ncu.gulimall.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<MemberRespVo>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行一些服务间的请求调用
        AntPathMatcher matcher = new AntPathMatcher();
        boolean matchStat = matcher.match("/order/order/status/**", request.getRequestURI());
        boolean matchPayed = matcher.match("/payed/notify", request.getRequestURI());
        if (matchStat || matchPayed) {
            return true;
        }

        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            //已经登陆
            loginUser.set(attribute);
            return true;
        } else {
            //没登录就去登陆
            request.getSession().setAttribute("msg", "请先进行登陆");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
